/**
 * Created by yiihua-013 on 16/10/30.
 *
 * 模拟减少一台服务器并请求
 */
'use strict'

require('json-comments')

const Memcached = require('memcached')

const cfg      = require('./memcached')
const nodes    = cfg.nodes
const strategy = cfg.distribute_strategy

const Mod  = require('./Mod')
const Hash = require('./ConsistentHash')

var diser = strategy === 'mod' ? new Mod() : new Hash()

var clientsPool = {
    'a': new Memcached(`${nodes['a'].host}:${nodes['a'].port}`),
    'b': new Memcached(`${nodes['b'].host}:${nodes['b'].port}`),
    'c': new Memcached(`${nodes['c'].host}:${nodes['c'].port}`),
    'd': new Memcached(`${nodes['d'].host}:${nodes['d'].port}`),
    'e': new Memcached(`${nodes['e'].host}:${nodes['e'].port}`)
};

// add servers
for (let nodeName in nodes) {
    diser.addNode(nodeName)
}

// 模拟减少一台服务器
diser.deleteNode('a')

// 每隔一段时间请求memcached中的key,如果不存在则重建缓存

var gen = function *(min,max) {
    for (let i = min;i < max;i++)
        yield i;
};

var g = gen(0,cfg.cnt)
var missCount = 0;
setTimeout(() => {
    setInterval(() => {
        let i          = g.next().value || cfg.cnt - 1;
        let key        = `${cfg.keyPrefix}${i}`;
        let serverName = diser.lookup(key);
        let client     = clientsPool[serverName];
        client.get(key, (err, value) => {
            if (err) console.error(err)
            if (!value) {
                client.set(key, `TEST_MEM_VALUE_${i}`, 0, (err, success) => {
                    if (err) console.error(err);
                    if (success) console.log(`重建缓存${key}成功,丢失缓存数量:${++missCount}`);
                });
            }
        });
    }, 40)
}, 3000);

